package com.qf.controller;

import com.qf.pojo.Admin;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @Author:zhangyang
 * @Date: 14:30
 * @Version 1.0
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //处理一下post乱码
        request.setCharacterEncoding("utf-8");

        //1.获取用户提交的参数
        //获取用户输入的验证码
        String code = request.getParameter("code");
        //1.1 校验 验证码
        //需要用户的输入验证码 和后台存储的验证码需要一致
        //需要获取session对象
        HttpSession session = request.getSession();
        //获取服务器端 存储的验证码
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        //验证码是一次性的;当前用户使用完毕,----产生新的验证码
        //将后台存储的CHECKCODE_SERVER,干掉
        session.removeAttribute("CHECKCODE_SERVER");

        if(!checkcode_server.equalsIgnoreCase(code)){

            //提示
            request.setAttribute("login_msg","验证码错误");
            //请求转发到登录页面上
            request.getRequestDispatcher("/login.jsp").forward(request,response);

            return ;
        }

        //


        // 封装Admin 管理员
        Admin admin = new Admin() ;
//        request.getParameter("username") ;  //举例注册:可能有十几条数据
        //当前用户提交的所有数据--Map集合中
        Map<String, String[]> map = request.getParameterMap();
        System.out.println(map);
        // public static void populate(Object bean, Map properties)
        //工具类
        try {
            BeanUtils.populate(admin,map); // admin.setUsername("jacky") ;  admin.setPassword("123456")
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        System.out.println(admin);

        //3.调用service 查询用户是否存在
        UserService userService = new UserServiceImpl() ;
       Admin loginAdmin =  userService.login(admin) ;
       if(loginAdmin!= null){
           //存在
           //将用户存储到session中
           session.setAttribute("loginAdmin",loginAdmin);
           request.getRequestDispatcher("/userInfo.jsp").forward(request,response);

       }else{
           //提示错误信息
           request.setAttribute("login_msg","用户名或者密码错误");
           request.getRequestDispatcher("/login.jsp").forward(request,response);
       }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
